/*
 * @Desc: 用户信息与 Token 管理
 * @Author: feim
 * @return: {Object}
 * @Date: 2022-06-22 19:15:30
*/
import Cookies from 'js-cookie'
export default {
  namespaced: true,
  state: {
    token: Cookies.get('id'),
    userInfo: {}
  },
  getters: {
    // 获取用户信息
    getUserInfo(state) {
      return state.userInfo;
    },

    // 获取token有效令牌
    getToken(state) {
      return state.token;
    }
  },
  actions: {
    setUserInfo({ commit }, user) {
      if (user.constructor === Object) {
        commit('mergeState', { userInfo: user });
      } else {
        throw new Error('userInfo is error Type, except a Object');
      }
    },

    setToken({ commit }, token) {
      if (typeof token === 'string') {
        Cookies.set('id', token)
        commit('mergeState', { token });
      } else {
        throw new Error('token is error Type, except a String');
      }
    }
  },
  mutations: {
    /**
     * 通用改变状态的值
     * @param {Object} state        状态
     * @param {Object} mergeObject  需要改变的对象 {key: value}
     */
    mergeState(state, mergeObject) {
      for (const key in mergeObject) {
        state[key] = mergeObject[key];
      }
    }
  }
};
